package com.huangyong.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.huangyong.entity.Article;
import com.huangyong.entity.User;
import com.huangyong.service.ArticleService;
import com.huangyong.service.UserService;

@Controller
@RequestMapping("/article")
public class ArticleController {

	@Autowired
	private ArticleService articleService;
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="allArticleBaseInfo")
	public String AllArticleBaseInfo(HttpSession session) {
		List<Article> articles = articleService.findAll();
		session.setAttribute("articles", articles);
		return "/admin/article/allArticle";
	}
	@RequestMapping(value="/deleteArticle/{aid}")
	public String deleteUser(@PathVariable("aid") int aid,HttpSession session) {
		String result = articleService.delete(aid);
		if(result.equals("success")) {
			session.setAttribute("articlemsg", "删除文章成功！");
		}else {
			session.setAttribute("articlemsg", "删除文章成功！");
		}
		return AllArticleBaseInfo(session);
	}
	
	@RequestMapping(value="/toUpdateArticle/{aid}")
	public String toUpdateArticle(@PathVariable("aid")int aid,HttpSession session) {
		session.setAttribute("aid", aid);
		Article article = articleService.findById(aid);
		session.setAttribute("article", article);
		return "/admin/article/updateArticle";
	}
	
	@RequestMapping(value="updateArticle")
	public String UpdateArticle(HttpSession session,String title,String author, String content,int readcount) {
		int aid = (int) session.getAttribute("aid");
		Article article = articleService.findById(aid);
		article.setTitle(title);
		article.setContent(content);
		article.setReadcount(readcount);
		User user = userService.findByUsername(author);
		article.setUser(user);
		
		articleService.update(article);
		return AllArticleBaseInfo(session);
	}
	
	@RequestMapping(value="addArticle")
	public String AddArticle(HttpSession session,String title,String author,String content,int readcount) {
		User user = userService.findByUsername(author);
		Article article = new Article(title,user,content,readcount);
		String result = articleService.insert(article);
		if(result.equals("success")) {
			session.setAttribute("addArticlemsg", "添加文章成功！");
		}else {
			session.setAttribute("addArticlemsg", "添加文章失败！");
		}
		return AllArticleBaseInfo(session);
	}
}
